﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameOfLife
{
    public class GameOfLifeRules
    {

        private int rowSize;
        private int columnSize;
        private bool[,] gameOfLifeBoard;
        
        public GameOfLifeRules(int boardRowSize, int boardColumnSize)
        {
            this.rowSize = boardRowSize;
            this.columnSize = boardColumnSize;
            gameOfLifeBoard = new bool[boardRowSize, boardColumnSize];
        }

        public bool[,] getGameBoard()
        {
            return gameOfLifeBoard;
        }


        public void initializeLifeInCell(int rowIndex, int columnIndex)
        {
            gameOfLifeBoard[rowIndex, columnIndex] = true;
        }

        public void nextTimeStep()
        {
            bool[,] nextTimeStepBoard = new bool[rowSize, columnSize];
            for (int rowIndex = 0; rowIndex < rowSize; rowIndex++)
            {
                for (int columnIndex = 0; columnIndex < columnSize; columnIndex++)
                {
                    int neighbourCount = neighbourLifeCount(rowIndex, columnIndex);
                    if (neighbourCount == 3)
                    {
                        nextTimeStepBoard[rowIndex, columnIndex] = true;
                    }
                    else if (neighbourCount == 2 && gameOfLifeBoard[rowIndex, columnIndex])
                    {
                        nextTimeStepBoard[rowIndex, columnIndex] = true;
                    }
                    else
                        nextTimeStepBoard[rowIndex, columnIndex] = false;
                }
            }
            gameOfLifeBoard = nextTimeStepBoard;
        }
        private int neighbourLifeCount(int rowIndex, int columnIndex)
        {
            //Console.WriteLine("Evaluating " + rowIndex.ToString() + "," + columnIndex.ToString());
            int lifeCount = 0;
            for (int i = Math.Max(0, rowIndex - 1); i < Math.Min(rowSize, rowIndex + 2); i++)
            {
                //Console.WriteLine("i= " + i.ToString());
                for (int k = Math.Max(0, columnIndex - 1); k < Math.Min(columnSize, columnIndex + 2); k++)
                {
                    //Console.WriteLine("k= " + k.ToString());
                    if (gameOfLifeBoard[i, k] && !(i == rowIndex && k == columnIndex))
                    {
                        lifeCount++;
                        //Console.WriteLine("Count goes up at " + i.ToString() + "," + k.ToString());
                    }
                }
            }
            return lifeCount;
        }
    }
}

